import { ref } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router';
import { useCookies } from '@vueuse/integrations/useCookies'
import { router } from '~/router/index';


export function useTabList() {
    const route = useRoute()


    const cookie = useCookies()
    console.log('route', route)
    const activeTab = ref(route?.path || '/')
    const tabList = ref([
        {
            title: '后台首页',
            path: '/',
        },

    ])

    onBeforeRouteUpdate((to, from) => {
        activeTab.value = to.path
        addTab({
            title: to.meta.title,
            path: to.path
        })
    })



    function addTab(tab) {

        let notTab = tabList.value.findIndex(t => t.path == tab.path) == -1
        if (notTab) {
            tabList.value.push(tab)
        }
        cookie.set("tabList", tabList.value)
    }

    const changeTab = (t) => {
        activeTab.value = t
        router.push(t)
    }

    const removeTab = (t) => {
        let tabs = tabList.value
        let a = activeTab.value
        if (a == t) {
            tabs.forEach((tab, index) => {
                if (tab.path == t) {
                    const nextTab = tabs[index + 1] || tabs[index - 1]
                    if (nextTab) {
                        a = nextTab.path
                    }
                }
            })
        }
        activeTab.value = a
        tabList.value = tabList.value.filter(tab => tab.path != t)
        cookie.set("tabList", tabList.value)
        changeTab(a)
    }

    function initTabList() {
        let tab = cookie.get("tabList")
        if (tab) {
            tabList.value = tab
        }
    }


    initTabList()

    const clearTabList = () => {
        cookie.remove("tabList")
    }

    const handleClose = (c) => {
        if (c == 'clearAll') {
            activeTab.value = '/'
            tabList.value = [
                {
                    title: '后台首页',
                    path: '/',
                },
            ]
            changeTab('/')
        } else if (c == 'clearOther') {
            tabList.value = tabList.value.filter(tab => tab.path == '/' || tab.path == activeTab.value)
            changeTab(activeTab.value)
        }
        cookie.set("tabList", tabList.value)
    }

    return {
        activeTab,
        tabList,
        changeTab,
        removeTab,
        handleClose,
        clearTabList,
    }
}